package com.unience.ec2.eclipse.view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;

import com.unience.ec2.eclipse.config.Config;
import com.xerox.amazonws.sdb.Domain;
import com.xerox.amazonws.sdb.Item;
import com.xerox.amazonws.sdb.ItemAttribute;
import com.xerox.amazonws.sdb.ListDomainsResult;
import com.xerox.amazonws.sdb.QueryResult;
import com.xerox.amazonws.sdb.SDBException;
import com.xerox.amazonws.sdb.SimpleDB;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
public class SimpleDbViewPart extends ViewPart implements SelectionListener {
	public static final String ID_VIEW = "com.unience.ec2.eclipse.view.SimpleDbViewPart"; //$NON-NLS-1$

	Composite composite1;

	private Table tableSimpleDb;
	private ToolBar toolBar;
	private ToolItem toolItem1;

	private SimpleDB sdb;
	private Composite composite2;
	private Button buttonRefresh;
	private Combo comboDomain;
	
	private Domain domain ;

	
	private static final String DELETE = "Delete";
	SimpleDbViewPart me;
	
	private ArrayList<String> headerAdded = new ArrayList<String>();

	/**
     * 
     */
	public SimpleDbViewPart() {
		super();
		// TODO Auto-generated constructor stub
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets
	 * .Composite)
	 */
	public void createPartControl(Composite parent) {
		parent.setSize(950, 700);
		{
			composite1 = new Composite(parent, SWT.NULL);
			GridLayout composite1Layout = new GridLayout();
			composite1Layout.makeColumnsEqualWidth = true;
			composite1Layout.horizontalSpacing = 1;
			composite1.setLayout(composite1Layout);
			{
				GridData composite2LData = new GridData();
				composite2LData.widthHint = 458;
				composite2LData.heightHint = 37;
				composite2 = new Composite(composite1, SWT.NULL);
				GridLayout composite2Layout = new GridLayout();
				composite2Layout.numColumns = 2;
				composite2.setLayout(composite2Layout);
				{
					comboDomain = new Combo(composite2, SWT.NONE);
					GridData comboDomainLData = new GridData();
					comboDomainLData.widthHint = 321;
					comboDomainLData.heightHint = 29;
					comboDomain.setLayoutData(comboDomainLData);
					comboDomain.setText("combo1");
				}
				{
					buttonRefresh = new Button(composite2, SWT.PUSH
							| SWT.CENTER);
					buttonRefresh.setText("refresh");
					buttonRefresh.addMouseListener(new MouseAdapter() {
						public void mouseDown(MouseEvent evt) {
							buttonRefreshMouseDown(evt);
						}
					});
				}
			}
			ImageDescriptor descriptor = null;
			{
				toolBar = new ToolBar(composite1, SWT.NONE);
				toolBar.setBounds(5, 5, 14, 14);
				{
					toolItem1 = new ToolItem(toolBar, SWT.NONE);
					
					toolItem1 = new ToolItem(toolBar, SWT.NONE);
					descriptor = ImageDescriptor.createFromFile(Config.class,
							"action_remove.png");
					toolItem1.setImage(descriptor.createImage());
					toolItem1.setText(DELETE);
					toolItem1.addSelectionListener(this);

				}
			}
			connect();
			loadDomain();
			{
				GridData tableElasticIPLData = new GridData();
				tableElasticIPLData.widthHint = 1200;
				tableElasticIPLData.heightHint = 600;
				tableElasticIPLData.verticalAlignment = GridData.BEGINNING;
				tableElasticIPLData.horizontalAlignment = GridData.BEGINNING;
				tableElasticIPLData.grabExcessHorizontalSpace = true;
				tableElasticIPLData.grabExcessVerticalSpace = true;

				tableSimpleDb = new Table(composite1, SWT.BORDER);
				tableSimpleDb.setLayoutData(tableElasticIPLData);

				
				tableSimpleDb.setHeaderVisible(true);

			}

		}

	}

	private void connect() {

		Config config = Config.getInstance();

		String acceskey = config.getKeyId();
		String secretkey = config.getSecretId();
		sdb = new SimpleDB(acceskey, secretkey, true);
		sdb.setSignatureVersion(0);
	}

	private void loadDomain() {

		ListDomainsResult list;
		try {
			list = sdb.listDomains();
			List<Domain> listDomain = list.getDomainList();

			for (Domain domain : listDomain) {

				comboDomain.add(domain.getName());

			}
		} catch (SDBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void loadData(String domainName) {

		try {
			domain = sdb.getDomain(domainName);
			QueryResult result = domain.listItems();
			List<Item> listItems = result.getItemList();

			for (Item item : listItems) {

				List<ItemAttribute> itemAttributes = item.getAttributes();

				for (ItemAttribute itemAttribute : itemAttributes) {
					String name = itemAttribute.getName();
					String value = itemAttribute.getValue();

				}

			}
		} catch (SDBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IWorkbenchPart#setFocus()
	 */
	public void setFocus() {
		// TODO Auto-generated method stub
	}

	/**
	 * Cleans up all resources created by this ViewPart.
	 */
	public void dispose() {
		super.dispose();
	}

	private void buttonRefreshMouseDown(MouseEvent evt) {
		System.out.println("buttonRefresh.mouseDown, event=" + evt);

		this.tableSimpleDb.removeAll();
		String domainName = this.comboDomain.getText();
		try {
			domain = this.sdb.getDomain(domainName);
			QueryResult result = domain.listItems();
			List<Item> itemList = result.getItemList();

			update(itemList);
		} catch (SDBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void addTableColumn(String name) {
		TableColumn tc1 = new TableColumn(tableSimpleDb, SWT.CENTER);

		tc1.setText(name);
		tc1.setWidth(180);
	}

	public void addItems2Table(final List<Item> itemList) {
		
		HashMap<String, Integer> order = new HashMap<String, Integer>();
		
	
		try {
			for (Item item : itemList) {

				List<ItemAttribute> itemAttributes;

				itemAttributes = item.getAttributes();

				String[] attributes = new String[itemAttributes.size()];
				int i = 0;
				int j = 0;
				//if (!addedHeaders) {;
					for (ItemAttribute itemAttribute : itemAttributes) {
						
						String header = itemAttribute.getName();
						if (headerAdded.indexOf(header)>=0){
							//log.info("Header already added " + header);
						}else{
							//Log.info("Header Not added " +header);
							this.addTableColumn(header);	
							order.put(header, new Integer(j++));
							headerAdded.add(header);
						}
						
						//añadimos los datos a la tabla
						String value = itemAttribute.getValue();
						int index = headerAdded.indexOf(header);
						if (value.length() < 80){							
							
							attributes[index] = value;							
						}else{
							//attributes[index] = value.substring(0, 80);	
						}

					}
					//addedHeaders = true;

			//	}if (integer != null){
					
					
				
				
				/*for (ItemAttribute itemAttribute : itemAttributes) {	
					
					String value = itemAttribute.getValue();
					if (value.length() < 80){
						Integer integer = order.get(itemAttribute.getName());
						if (integer != null){
							try{
								attributes[integer.intValue()] = value;
							}catch(Throwable e){
								e.printStackTrace();
							}
							
						}
					}

				}
				*/

				TableItem itemAux = new TableItem(this.tableSimpleDb, SWT.NONE);
				itemAux.setText(attributes);
				itemAux.setData(item);

			}
			
			tableSimpleDb.redraw();
			

		} catch (SDBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void update(final List<Item> itemList) {

		me = this;

		Config.getInstance().getDisplay().asyncExec(new Runnable() {
			public void run() {

				final IWorkbench workbench = PlatformUI.getWorkbench();
				if (workbench == null)
					return;
				final Display display = workbench.getDisplay();

				if (!display.isDisposed()) {

					me.addItems2Table(itemList);
				}
			}
		});

	}

	public void widgetDefaultSelected(SelectionEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void widgetSelected(SelectionEvent e) {
		Object obj = e.getSource();

		if (obj instanceof ToolItem) {
			ToolItem toolItem = (ToolItem) obj;

			if (DELETE.equals(toolItem.getText())) {

				TableItem item = getSelectedItem();
				if (item != null) {
					Object data = item.getData();
					if (data instanceof Item) {
						 Item ite  = (Item) data;

						
							try {
								System.out.println("deleting : " + ite.getIdentifier());
								domain.deleteItem(ite.getIdentifier());
								
							} catch (SDBException ee) {
								ee.printStackTrace();
							}
						
					}					

				}

			}
		}
		
	}
	
	private TableItem getSelectedItem() {
		TableItem item[] = tableSimpleDb.getSelection();
		for (TableItem tableItem : item) {

			return tableItem;

		}

		return null;
	}

}
